#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "conf.h"

/* Gets the configuration for the server from a file.
 * If no IP is specified in the configuration file, ip is set to NULL.
 * It returns the number of ports the server must listen, or less than zero if
 * an error has occured */
int
getConf(char * file, int * port, char * ip, int * connections, char * dbname)
{
	FILE * f;
	int n;
	char c;
	char par[MAX_PAR], val[MAX_VAL];
	int nports = 0, nip = 0;
	
	if ((f = fopen(file, "r")) == NULL)
	{
		fprintf(stderr, "Error opening configuration file\n");
		return -1;
	}
	
	/* get all the initial comment */
	while ((c = fgetc(f)) != '#');
	
	for (n = 2; n == 2 && (n = fscanf(f, "%s = %s\n", par, val)) != EOF; )
	{
		/* port parsed */
		if (strcmp(CONF_PORT, par) == 0)
			port[nports++] = atoi(val);
		
		/* IP parsed */
		else if (strcmp(CONF_IP, par) == 0)
		{
			strcpy(ip, val);
			nip++;
		}
		
		/* connections parsed */
		else if (strcmp(CONF_CONN, par) == 0)
			*connections = atoi(val);
		
		/* database name parsed */
		else if (strcmp(CONF_DB, par) == 0)
			strcpy(dbname, val);
		
		else
		{
			n = 0;
			fprintf(stderr, "Configuration file is malformed\n");
			return -1;
		}
	}
	
	/* no IP specified in configuration file */
	if (nip == 0 || strcmp(CONF_ALL, ip) == 0)
		strcpy(ip, DEFAULT_HOST);
	
	return nports;
}

void
parseConf(int argc, char * argv[], int * port, char * ip, int * connections,
		  char * dbname)
{
	printf("Configuration must be parsed here\n");
}

/*
 int
 main(void)
 {
 int port[MAX_PORTS];
 char ip[MAX_IP_LEN];
 int connections;
 char dbname[MAX_FILEL];
 
 int n, i;
 
 n = getConf(CONF_FILE, port, ip, &connections, dbname);
 
 for (i=0; i<n; i++)
 printf("port = %d\n", port[i]);
 printf("ip = %s\n", ip);
 printf("connections = %d\n", connections);
 printf("db filename = %s\n", dbname);
 
 return 0;
 }
 */
